/*
 * server.c
 *
 *  Created on: Oct 22, 2009
 *      Author: thienlong
 */

#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include "config.h"
#include "log.h"
#include "server.h"
#include "reuse-data.h"
#include <pthread.h>
#include <signal.h>
#include <time.h>

ServerConf *conf = NULL;
extern const int SOCKET_ADRR_SIZE;

void run() {
	conf = load_config();
	if (!conf) {
		fprintf_log(LOG_ERROR, "[%s] %s() %d: Can't load configuration",
				__FILE__, __FUNCTION__, __LINE__);
		exit(EXIT_FAILURE);
	}
	set_log_config(conf->log_file, conf->log_level, conf->log_maxbytes,
			conf->log_maxbackup);
	int listener = server_init(conf->httpPort, conf->httpPending);
	worker_thread_init(conf);
	struct event_base *base = event_base_new();
	if (base == NULL) {
		fprintf_log(LOG_ERROR, "[%s] %s() %d: Can't allocate event_base",
				__FILE__, __FUNCTION__, __LINE__);
		exit(1);
	}
	struct event *listen_event = event_new(base, listener,
			EV_READ | EV_PERSIST, do_accept, NULL);
	if (event_add(listen_event, NULL) < 0) {
		fprintf_log(LOG_ERROR, "[%s] %s() %d: Can't monitor the listen_event",
				__FILE__, __FUNCTION__, __LINE__);
		exit(1);
	}
	time_t t = time(NULL);
	fprintf_log(LOG_INFO, "server was started at %s", ctime(&t));
	event_base_dispatch(base);
}

int main(int argc, char **argv) {
	run();
	close_logfile();
	return 0;
}
